Skip to main content

Code blocks

Code blocks within documentation are super-powered .

Code title

You can add a title to the code block by adding a title key after the language (leave a space between them).

/src/components/HelloCodeTitle.js
function HelloCodeTitle(props) {
return <h1>Hello, {props.name}</h1>;
}

Syntax highlighting

Code blocks are text blocks wrapped around by strings of 3 backticks. You may check out this reference for the specifications of MDX.

console.log('Every repo must come with a mascot.');

Use the matching language meta string for your code block, and Docusaurus will pick up syntax highlighting automatically, powered by Prism React Renderer.

Theming

By default, the Prism syntax highlighting theme we use is Palenight. You can change this to another theme by passing theme field in prism as themeConfig in your docusaurus.config.js.

For example, if you prefer to use the dracula highlighting theme:

docusaurus.config.js
import {themes as prismThemes} from 'prism-react-renderer';

export default {
themeConfig: {
prism: {
theme: prismThemes.dracula,
},
},
};

Because a Prism theme is just a JS object, you can also write your own theme if you are not satisfied with the default. Docusaurus enhances the github and vsDark themes to provide richer highlight, and you can check our implementations for the light and dark code block themes.

Supported Languages

By default, Docusaurus comes with a subset of commonly used languages. Some popular languages like Java, C#, or PHP are not enabled by default. To add syntax highlighting for any of the other Prism-supported languages, define it in an array of additional languages.

For example, if you want to add highlighting for the PowerShell language:

docusaurus.config.js
export default {
// ...
themeConfig: {
prism: {
additionalLanguages: ['powershell'],
},
// ...
},
};

After adding additionalLanguages, restart Docusaurus.

If you want to add highlighting for languages not yet supported by Prism, you can swizzle prism-include-languages:

npm run swizzle @docusaurus/theme-classic prism-include-languages

It will produce prism-include-languages.js in your src/theme folder. You can add highlighting support for custom languages by editing prism-include-languages.js:

src/theme/prism-include-languages.js
const prismIncludeLanguages = (Prism) => {
// ...
additionalLanguages.forEach((lang) => {
require(`prismjs/components/prism-${lang}`);
});
require('/path/to/your/prism-language-definition');
// ...
};

Line highlighting

Highlighting with comments

You can use comments with highlight-next-line, highlight-start, and highlight-end to select which lines are highlighted.

function HighlightSomeText(highlight) {
if (highlight) {
return 'This text is highlighted!';
}
return 'Nothing highlighted';
}

function HighlightMoreText(highlight) {
if (highlight) {
return 'This range is highlighted!';
}
return 'Nothing highlighted';
}

Supported commenting syntax:

  • /* ... */
  • // ...
  • {/* ... */}
  • # ...
  • <!-- ... -->

We will do our best to infer which set of comment styles to use based on the language.

Highlighting with metadata string

You can also specify highlighted line ranges within the language meta string (leave a space after the language). To highlight multiple lines, separate the line numbers by commas or use the range syntax to select a chunk of lines.

import React from 'react';

function MyComponent(props) {
if (props.isBar) {
return <div>Bar</div>;
}

return <div>Foo</div>;
}

export default MyComponent;

Custom magic comments

You can declare custom magic comments through theme config. For example, you can register another magic comment that adds a code-block-error-line class name:

docusaurus.config.js
export default {
themeConfig: {
prism: {
magicComments: [
// Remember to extend the default highlight class name as well!
{
className: 'theme-code-block-highlighted-line',
line: 'highlight-next-line',
block: {start: 'highlight-start', end: 'highlight-end'},
},
{
className: 'code-block-error-line',
line: 'This will error',
},
],
},
},
};

And style it in your CSS:

src/css/custom.css
.code-block-error-line {
background-color: #ff000020;
display: block;
margin: 0 calc(-1 * var(--ifm-pre-padding));
padding: 0 var(--ifm-pre-padding);
border-left: 3px solid #ff000080;
}

Usage:

const name = null;
// This will error
console.log(name.toUpperCase());
// Uncaught TypeError: Cannot read properties of null (reading 'toUpperCase')

Line numbering

You can enable line numbering for your code block by using showLineNumbers key within the language meta string.

import React from 'react';

export default function MyComponent(props) {
return <div>Foo</div>;
}

Interactive code editor

(Powered by React Live)

You can create an interactive coding editor with the @docusaurus/theme-live-codeblock plugin.

First, install the plugin:

npm install --save @docusaurus/theme-live-codeblock

Add it to your config:

docusaurus.config.js
export default {
// ...
themes: ['@docusaurus/theme-live-codeblock'],
// ...
};

To use it, add live to the language meta string:

function Clock(props) {
const [date, setDate] = useState(new Date());
useEffect(() => {
const timerID = setInterval(() => tick(), 1000);
return function cleanup() {
clearInterval(timerID);
};
});
function tick() {
setDate(new Date());
}
return (
<div>
<h2>It is {date.toLocaleTimeString()}.</h2>
</div>
);
}

Imports

It is not possible to import components directly from the react-live code editor; you have to define available imports upfront. By default, all React imports are available. If you need others, swizzle the scope:

npm run swizzle @docusaurus/theme-live-codeblock ReactLiveScope -- --eject

Imperative Rendering (noInline)

The noInline option should be used to avoid errors when your code spans multiple components or variables.

const project = 'Docusaurus';

const Greeting = () => <p>Hello {project}!</p>;

render(<Greeting />);

Using JSX markup in code blocks

Code block in Markdown always preserves its content as plain text. If you want to embed HTML markup, use <pre>, <code>, or <CodeBlock>.

<pre>
<b>Input: </b>1 2 3 4{'\n'}
<b>Output: </b>"366300745"{'\n'}
</pre>

Multi-language support code blocks

We've implemented a general-purpose <Tabs> component in the classic theme.

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

<Tabs>
<TabItem value="js" label="JavaScript">
```js
function helloWorld() {
console.log('Hello, world!');
}
```
</TabItem>
<TabItem value="py" label="Python">
```py
def hello_world():
print("Hello, world!")
```
</TabItem>
<TabItem value="java" label="Java">
```java
class HelloWorld {
public static void main(String args[]) {
System.out.println("Hello, World");
}
}
```
</TabItem>
</Tabs>

Docusaurus npm2yarn remark plugin

Displaying CLI commands in both npm and Yarn is a very common need. Docusaurus provides a utility for this.

Install:

npm install @docusaurus/remark-plugin-npm2yarn

Configure docusaurus.config.js:

export default {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
remarkPlugins: [
[require('@docusaurus/remark-plugin-npm2yarn'), {sync: true}],
],
},
// ...
},
],
],
};

Usage:

npm install @docusaurus/remark-plugin-npm2yarn

Usage in JSX

Outside of Markdown, you can use the @theme/CodeBlock component to get the same output.

import CodeBlock from '@theme/CodeBlock';

export default function MyReactPage() {
return (
<div>
<CodeBlock
language="jsx"
title="/src/components/HelloCodeTitle.js"
showLineNumbers>
{`function HelloCodeTitle(props) {
return <h1>Hello, {props.name}</h1>;
}`}
</CodeBlock>
</div>
);
}